package com.my.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.my.framework.web.filters.MyFilter;
import com.my.framework.web.filters.MyFilterProperties;
import com.my.framework.web.filters.QueueFilter;
import com.my.framework.web.filters.StatistFilter;
import com.my.utils.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Configuration
@EnableConfigurationProperties(MyFilterProperties.class)
@Slf4j
public class MyFilterAutoConfiguration {

	MyFilterProperties properties;
	List<String> exclusions;
 
	public MyFilterAutoConfiguration(MyFilterProperties properties) {
		this.properties = properties;
		exclusions=getFormatUrl(properties.getExclusions());
		log.debug("要忽略的前缀:"+this.exclusions);
	}

	@Bean
	@ConditionalOnProperty(name = MyFilterProperties.FILTER, matchIfMissing = true)
	public MyFilter myFilter() {
		List webFilters = new ArrayList();
		if (properties.statis) {
			List<String> igs=getFormatUrl(properties.ignoreLog);
			webFilters.add(new StatistFilter(properties.getMonitorPage(),igs));
		}
		if (properties.queue && properties.limit != null && properties.limit.size() > 0) {
			QueueFilter f = new QueueFilter(properties.getLimitMap());
			webFilters.add(f);
		}
		log.debug("创建自定义过滤器:"+webFilters);
		MyFilter filter = new MyFilter(webFilters, this::isFilter);
		return filter;
	}

	// 是否过滤某个链接
	public boolean isFilter(String url) {
		for (String s : exclusions) {
			if (url.startsWith(s)) {
				return false;
			}
		}
		return true;
	}

	private List<String> getFormatUrl(String url){
		List list=new ArrayList();
		url=url.trim();
		if(StringUtil.isEmpty(url)) {
			return list;
		}
		for(String s:url.split(",")) {
			String x=s.trim();
			if(StringUtil.isNotEmpty(x)) {
				if(!x.startsWith("/")) {
					x="/"+x;
				}
				list.add(x);
			}
		}
		return list;
	}
}
